package util;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

public class Util {
    //向指定地址发送post请求
    public  static  String post(String url,String data){
        try {
            URL url1Obj=new URL(url);
            URLConnection connection= url1Obj.openConnection();
            connection.setDoOutput(true);
            //获取输出流
            OutputStream os=connection.getOutputStream();
            //写出数据
            os.write(data.getBytes());
            os.close();
            //获取输入流
            InputStream is=connection.getInputStream();
            byte[] b=new byte[1024];
            int len;
            StringBuilder sb=new StringBuilder();
            while ((len=is.read(b))!=-1){
                sb.append(new String(b,0,len));
            }
            return sb.toString();

        }catch (Exception e){
            e.printStackTrace();
        }

        return  null;
    }

    //向指定地址发送get请求
    public static  String get(String url){
        try {
            URL url1Obj=new URL(url);
            URLConnection connection= url1Obj.openConnection();
            InputStream is=connection.getInputStream();
            byte[] b=new byte[1024];
            int len;
            StringBuilder sb=new StringBuilder();
            while ((len=is.read(b))!=-1){
                sb.append(new String(b,0,len));
            }
            return sb.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
